﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Net;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using CeskyRozhlasRT.DataModel;

namespace CeskyRozhlasRT.Parsing
{
    public class ShowsRetriever: IShowsRetriever
    {
        public class ParserState
        {
            public Collection<RadioShow> Shows;
            public HttpWebRequest Request;
        }

        public void ParseXmlShowsList(RadioSchedule iSchedule)
        {
            var parserState = new ParserState
            {
                Shows = iSchedule.Shows
            };
            ParseXmlShowsList(iSchedule.Uris, parserState);
        }

        public void ParseXmlShowsList(IEnumerable<string> iUris, ParserState parserState)
        {
            foreach (var aUri in iUris)
            {
                try
                {
                    using (var aReader = StationsRetriever.AssetManager.GetXmlReader(aUri))
                    {
                        ParseXmlShowsList(aReader, parserState);
                    }
                }
                catch (Exception e)
                {
                    //Oops... something happened.... We should register that to intellitrace
                }
            }
        }

        public static void ParseXmlShowsListAsync(RadioSchedule iSchedule)
        {

            foreach (var aUri in iSchedule.Uris)
            {

                var parserState = new ParserState
                {
                    Shows = iSchedule.Shows
                };


                var request = (HttpWebRequest)WebRequest.Create(aUri);
                request.BeginGetResponse(WebResponseCallback, new ParserState
                {
                    Shows = iSchedule.Shows,
                    Request = request,
                });
            }
        }

        private static void WebResponseCallback(IAsyncResult iAsyncResult)
        {
            var asyncData = iAsyncResult.AsyncState as ParserState;
            if (asyncData != null)
            {
                var response = asyncData.Request.EndGetResponse(iAsyncResult) as HttpWebResponse;
                if (response != null)
                {
                    ParseXmlShowsList(XmlReader.Create(response.GetResponseStream()), asyncData);
                }
            }
        }


        public static void ParseXmlShowsList(XmlReader iReader, ParserState parserState)
        {
            var aDocument = XDocument.Load(iReader);
            foreach (var aCurrentElement in aDocument.Descendants(XName.Get("porad")))
            {
                try
                {
                    var aTimeDetails = aCurrentElement.Element("casvysilani");
                    var aDatePattern = aTimeDetails.Value;
                    int aStartTime = 0;
                    Int32.TryParse(aTimeDetails.Attribute("od").Value, out aStartTime);
                    Int32 aStopTime = 0;
                    Int32.TryParse(aTimeDetails.Attribute("do").Value, out aStopTime);
                    var aCurrentDate = DateTime.ParseExact(aDatePattern, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture).Date; 
                    //Could have called .ToUniversalTime(); here, to convert to UTC, but it won't work on Azure, so rather don't even try to change the date:)
                    var aShow = new RadioShow
                    {
                        Title = aCurrentElement.Element("nazev").Value,
                        Description = aCurrentElement.Element("popis").Value,
                        Type = aCurrentElement.Element("typporadu_nazev").Value,
                        StopTime = aCurrentDate.AddSeconds(aStopTime),
                        StartTime = aCurrentDate.AddSeconds(aStartTime)
                    };
                    if (aShow.HasValidContent())
                    {
                        parserState.Shows.Add(aShow);
                    }
                }
                catch (Exception)
                {
                    //ignore all parsing errors 
                }
            }
        }

    }

    public interface IShowsRetriever
    {
    }
}
